#!/usr/bin/python3
# -*- coding:utf-8 -*-
#向平台已经创建的数据流发送数据点
'''
#=============================================================================
#     FileName: views.py
#         Desc: 
#       Author: wangheng
#        Email: wujiwh@gmail.com
#     HomePage: http://wangheng.org
#      Version: 0.0.1
#   LastChange: 2015-01-14 13:46:29
#      History:
#=============================================================================
'''
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from contextlib import closing
from pi_car import app
import re
import RPi.GPIO as GPIO
import time
import math
import threading #
from PID import PID 



counter=0
frq=500
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(15,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)

GPIO.setup(13, GPIO.IN)


pwm_11 = GPIO.PWM(11,frq)
pwm_12 = GPIO.PWM(12,frq)
pwm_15 = GPIO.PWM(15,frq)
pwm_16 = GPIO.PWM(16,frq)

pwm_11.start(0)
pwm_12.start(0)
pwm_15.start(0)
pwm_16.start(0)

def my_callback(channel):
    global counter
    counter+=1
GPIO.add_event_detect(13, GPIO.RISING, callback=my_callback)#


#定义函数
def fun_timer():
    global counter
    print(counter)
    pid.update(counter)
    output = pid.output
    
    counter=0
    global timer  #定义变量
    timer = threading.Timer(0.3,fun_timer)   #60秒调用一次函数
    #定时器构造函数主要有2个参数，第一个参数为时间，第二个参数为函数名
    timer.start()    #启用定时器　　

timer = threading.Timer(0.3,fun_timer)  #首次启动
#timer.start()
pid = PID.PID(0.2, 0, 0)
pid.SetPoint=15

@app.route('/')
def show_index():
    return render_template('home.html')

@app.route("/login", methods=["GET", "POST"])                                   
def login():                                                                    
    if request.method=="GET":                                                   
        return "get"+request.form["user"]
    elif request.method=="POST":
        #print(request.get_data())
        r = int(float(request.form['r']))
        x = int(float(request.form['x']))
        y = int(float(request.form['y']))
        #print(x,y,r)
        run(x, y, r)
        #print(request.form['x'])
        return "post"

@app.route('/ctl',methods=['GET','POST'])
def ctrl_id():
    if request.method == 'POST':
        id=request.form['id']
        #global counter
        #print(counter)
        #counter=0
        pwm_11.start(0)
        pwm_12.start(0)
        pwm_15.start(0)
        pwm_16.start(0)

        if id == 't_left':                        
            t_left()
            #time.sleep(0.3)
            #t_stop()
            return "left"
        elif id == 't_right':
            t_right()
            #time.sleep(0.3)
            #t_stop()
            return "right"
        elif id == 't_up':
            t_up()          
            return "up"
        elif id == 't_down':
            t_down()
            return "down"
        elif id == 't_stop':
            t_stop()
            return "stop"
    return redirect(url_for('show_index'))

def t_stop():
        pwm_11.ChangeDutyCycle(0)
        pwm_12.ChangeDutyCycle(0)
        pwm_15.ChangeDutyCycle(0)
        pwm_16.ChangeDutyCycle(0)

def t_up():
        pwm_12.ChangeDutyCycle(0)
        pwm_11.ChangeDutyCycle(50)
        pwm_16.ChangeDutyCycle(0)
        pwm_15.ChangeDutyCycle(50)
        #GPIO.output(11, True)
    #GPIO.output(12, False)
    #GPIO.output(15, True)
    #GPIO.output(16, False)

def t_down():
        pwm_11.ChangeDutyCycle(0)
        pwm_12.ChangeDutyCycle(50)
        pwm_15.ChangeDutyCycle(0)
        pwm_16.ChangeDutyCycle(50)
    #GPIO.output(11, False)
    #GPIO.output(12, True)
    #GPIO.output(15, False)
    #GPIO.output(16, True)

def t_left():
        pwm_11.ChangeDutyCycle(0)
        pwm_12.ChangeDutyCycle(0)
        pwm_16.ChangeDutyCycle(0)
        pwm_15.ChangeDutyCycle(35)
    #GPIO.output(11, False)
    #GPIO.output(12, True)
    #GPIO.output(15, True)
    #GPIO.output(16, False)

def t_right():
        pwm_12.ChangeDutyCycle(0)
        pwm_11.ChangeDutyCycle(35)
        pwm_15.ChangeDutyCycle(0)
        pwm_16.ChangeDutyCycle(0)
    #GPIO.output(11, True)
    #GPIO.output(12, False)
    #GPIO.output(15, False)
    #GPIO.output(16, True)

def run(x, y, r):    
    t = abs(x) * 100.0 / r
    if t < 20:  # 电压太小，驱动不起来
        t = 20 
    if y < 180:
        t_up()
        pwm_r=pwm_15
        pwm_l=pwm_11    
        if y >90: # 往左边偏, 右轮的速度比左轮快
            t2 = t * (180-y) / 90
            if t2 < 20:  # 电压太小，驱动不起来
                t2 = 20 
            pwm_r.ChangeDutyCycle(t)
            pwm_l.ChangeDutyCycle(t2)
        else: # 往右边偏, 左边的速度比右轮快
            t2 = t * y / 90                   
            if t2 < 20:  # 电压太小，驱动不起来
                t2 = 20 
            pwm_l.ChangeDutyCycle(t)
            pwm_r.ChangeDutyCycle(t2)    
    elif y > 180:
        y=y-180
        t_down()
        pwm_r=pwm_16
        pwm_l=pwm_12  
        
        if y >90: # 往左边偏, 右轮的速度比左轮快
            t2 = t * (180-y) / 90
            if t2 < 20:  # 电压太小，驱动不起来
                t2 = 20 
            pwm_r.ChangeDutyCycle(t2)
            pwm_l.ChangeDutyCycle(t)
        else: # 往右边偏, 左边的速度比右轮快
            t2 = t * y / 90
            if t2 < 20:  # 电压太小，驱动不起来
                t2 = 20 
            pwm_l.ChangeDutyCycle(t2)
            pwm_r.ChangeDutyCycle(t)
              
    else:
        t_stop()
        return  
            
   
    print (x, y, t, t2)
'''    if x * x + y * y > r * r:
        return
    speed_min = 15
    speed_max = 100
    speed_delta = speed_max - speed_min

    if y < 0:
        t_up()
        pwm_r=pwm_15
        pwm_l=pwm_11
        
    elif y > 0:
        t_down()
        pwm_r=pwm_16
        pwm_l=pwm_12
        
    else:
        t_stop()
        return
 
    t = abs(y) * 100.0 / r
    if t < 20:  # 电压太小，驱动不起来
        t = 20 
    d = math.atan2(x, y) * 180 / math.pi
    
    if x < 0: # 往左边偏, 右轮的速度比左轮快
        t2 = t * (abs(90 + d) / 90)
        if t2 < 20:  # 电压太小，驱动不起来
            t2 = 20 
        pwm_r.ChangeDutyCycle(t)
        pwm_l.ChangeDutyCycle(t2)
    else: # 往右边偏, 左边的速度比右轮快
        t2 = t * (abs(90 - d) / 90)
        if t2 < 20:  # 电压太小，驱动不起来
            t2 = 20 
        pwm_l.ChangeDutyCycle(t)
        pwm_r.ChangeDutyCycle(t2)
    print (x, y, t, t2)
    '''



